package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.AlertDataHandleDto;
import com.zzyl.dto.AlertDataPageQueryDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.User;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.AlertDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class AlertDataServiceImpl implements AlertDataService {

    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageBean<AlertDataVo> pageQuery(AlertDataPageQueryDto dto) {


        LocalDateTime minCreateTime = null;
        LocalDateTime maxCreateTime = null;

        if (ObjectUtil.isNotEmpty(dto.getStartTime())) {
            minCreateTime = LocalDateTimeUtil.of(dto.getStartTime());

        }
        //处理结束时间
        if (ObjectUtil.isNotEmpty(dto.getEndTime())) {
            maxCreateTime = LocalDateTimeUtil.of(dto.getEndTime());

        }

        Page<AlertDataVo> alertDataVos = alertDataMapper.adminPageQuery(dto.getId(),dto.getStatus(),dto.getDeviceName(),
                ThreadLocalUtil.get(),minCreateTime,maxCreateTime);

        return PageBean.of(alertDataVos,AlertDataVo.class);
    }

    /**
     * 处理报警数据
     *
     * @param id
     * @param dto
     */
    @Override
    public void handleAlertData(Long id, AlertDataHandleDto dto) {
        //根据id查询数据
        AlertData alertData = alertDataMapper.selectByPrimaryKey(id);
        //找出和该条报警数据同时发生的其它数据（iot_id、alarm_time、alert_rule_id、status）
        //获取当前登录人的信息
        Long userId = ThreadLocalUtil.get();
        User user = userMapper.selectByPrimaryKey(userId);

        List<AlertData> list = alertDataMapper.selectByAlertData(alertData);

        for (AlertData data : list) {
            //将dto数据封装到alertData
            BeanUtil.copyProperties(dto, data);

            data.setProcessorId(userId);
            data.setProcessorName(user.getRealName());
            data.setStatus(1);//状态
            //更新数据库数据

            alertDataMapper.updateByPrimaryKeySelective(data);
        }
    }
}
